// 主进程日志记录工具类
import fs from 'fs'
import path from 'path'
import { app } from 'electron'

export enum LogLevel {
  DEBUG = 0,
  INFO = 1,
  WARN = 2,
  ERROR = 3
}

export class Logger {
  private static instance: Logger
  private logLevel: LogLevel = LogLevel.DEBUG
  private logFilePath: string

  private constructor() {
    // 创建日志目录
    const logDir = path.join(app.getPath('userData'), 'logs')
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir, { recursive: true })
    }
    
    // 设置日志文件路径
    this.logFilePath = path.join(logDir, `app-${new Date().toISOString().slice(0, 10)}.log`)
  }

  static getInstance(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger()
    }
    return Logger.instance
  }

  setLogLevel(level: LogLevel): void {
    this.logLevel = level
  }

  debug(message: string, ...args: any[]): void {
    if (this.logLevel <= LogLevel.DEBUG) {
      this.log('DEBUG', message, ...args)
    }
  }

  info(message: string, ...args: any[]): void {
    if (this.logLevel <= LogLevel.INFO) {
      this.log('INFO', message, ...args)
    }
  }

  warn(message: string, ...args: any[]): void {
    if (this.logLevel <= LogLevel.WARN) {
      this.log('WARN', message, ...args)
    }
  }

  error(message: string, ...args: any[]): void {
    if (this.logLevel <= LogLevel.ERROR) {
      this.log('ERROR', message, ...args)
    }
  }

  private log(level: string, message: string, ...args: any[]): void {
    const now = new Date()
    const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}.${String(now.getMilliseconds()).padStart(3, '0')}`
    const logMessage = `[${timestamp}] [${level}] ${message}`
    
    // 控制台输出
    switch (level) {
      case 'DEBUG':
        console.debug(logMessage, ...args)
        break
      case 'INFO':
        console.info(logMessage, ...args)
        break
      case 'WARN':
        console.warn(logMessage, ...args)
        break
      case 'ERROR':
        console.error(logMessage, ...args)
        break
      default:
        console.log(logMessage, ...args)
    }
    
    // 写入日志文件
    try {
      const logEntry = `${logMessage} ${args.map(arg => JSON.stringify(arg)).join(' ')}\n`
      fs.appendFileSync(this.logFilePath, logEntry)
    } catch (error) {
      // 如果写入文件失败，只在控制台输出错误
      console.error('写入日志文件失败:', error)
    }
  }
}

// 创建默认实例
export const logger = Logger.getInstance()